package com.nx.platform.es.biz.esspider.handler;

import com.nx.platform.es.biz.esspider.expression.Expression;
import com.nx.platform.es.biz.esspider.entity.Item;
import com.nx.platform.es.common.utils.MoreMaps;

import java.util.Map;

/**
 * @author
 * @date 2018/01/5
 */
@HandlerDefine(HandlerType.SIMPLE)
public class SimpleOptypeDeterminantHandler extends AbstractSimpleHandler {

    private Expression discard;
    private Expression delete;
    private boolean updateOnly;

    @Override
    public void init(Map<?, ?> settings) throws Exception {
        this.discard = Expression.create(MoreMaps.getString(settings, "discard"));
        this.delete = Expression.create(MoreMaps.getString(settings, "delete"));
        this.updateOnly = MoreMaps.getBooleanValue(settings, "updateOnly", false);
    }

    @Override
    public void handle(Map<Long, Item> items) throws Exception {
        items.forEach((key, value) -> {
            if (discard.eval(value.getDoc())) {
                value.setOpType(Item.OpType.DISCARD);
            } else if (delete.eval(value.getDoc())) {
                value.setOpType(Item.OpType.DELETE);
            } else {
                value.setOpType(updateOnly ? Item.OpType.UPDATE : Item.OpType.UPSERT);
            }
        });
    }

}
